package me.mstsc;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import lombok.Getter;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @author langle
 * @version 1.0
 */
@Getter
public class MstscManager {

    private static final File JSON_FILE = new File("mstsc.json");
    private static final String REGISTRY_ROOT = "HKEY_CURRENT_USER\\Software\\Microsoft\\Terminal Server Client";
    private static final String REGISTRY_DEFAULT = REGISTRY_ROOT + "\\Default";
    private static final String REGISTRY_SERVERS = REGISTRY_ROOT + "\\Servers";

    private static MstscManager instance;

    public static MstscManager getInstance() {
        if (instance == null) instance = new MstscManager();
        return instance;
    }

    private final List<Account> accounts = new ArrayList<>();

    public MstscManager() {
        JSONObject json = new JSONObject();
        if (JSON_FILE.exists()) {
            try (FileInputStream input = new FileInputStream(JSON_FILE)) {
                json = JSON.parseObject(input, StandardCharsets.UTF_8);
            } catch (IOException e) {
                e.printStackTrace(System.err);
                return;
            }
        } else {
            JSONArray array = new JSONArray();
            Account defaultAccount = new Account("127.0.0.1", "administrator", "123456789");
            array.add(defaultAccount.toJSONObject());
            json.put("mstsc", array);
            try (FileOutputStream output = new FileOutputStream(JSON_FILE)) {
                JSON.writeTo(output, json, JSONWriter.Feature.PrettyFormat);
            } catch (IOException e) {
                e.printStackTrace(System.err);
                return;
            }
        }
        JSONArray array = json.getJSONArray("mstsc");
        for (int i = 0; i < array.size(); i++) {
            JSONObject jsonAccount = array.getJSONObject(i);
            Account account = Account.fromJSONObject(jsonAccount);
            this.accounts.add(account);
        }
    }

    public void connect(Account account) throws IOException {
        Runtime runtime = Runtime.getRuntime();
        runtime.exec("cmdKey /generic:termsrv/" + account.getAddress() + " /user:" + account.getUserName() + " /pass:" + account.getPassword());
        runtime.exec("cmd.exe /c mstsc /v:" + account.getComputer());
    }

    public void clear() throws IOException {
        Runtime runtime = Runtime.getRuntime();

        runtime.exec(String.format("REG DELETE \"%s\" /f", REGISTRY_DEFAULT));

        Process process = runtime.exec(String.format("REG QUERY \"%S\"", REGISTRY_SERVERS));
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

        String line;
        while ((line = reader.readLine()) != null) {
            if (line.isEmpty()) continue;
            runtime.exec("REG DELETE \"" + line + "\" /f");
            runtime.exec("cmdKey /delete:termsrv/" + line.substring(line.lastIndexOf("\\") + 1));
        }
    }

}
